package com.traitswu.websocket.dmxlog.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaoquan on 17-5-27.
 */


@ServerEndpoint("/dmxlog/{loggerName}")
public class DmxLogEndpoint {
    private static final Logger LOGGER = LoggerFactory.getLogger(DmxLogEndpoint.class);

    private DmxLogWebSocketPipe pipe = DmxLogWebSocketPipe.getInstance();
    private static Session curSession;
    public static ScheduledExecutorService pingPongTest = Executors.newSingleThreadScheduledExecutor();

    public DmxLogEndpoint() {
        pingPongTest.scheduleWithFixedDelay(()->doTest(), 5, 10, TimeUnit.SECONDS);

    }


    private static  void doTest() {
        System.out.println("Ping Start============>>>>>>>>>>");
        if (curSession != null) {
          /*  try {
                //如果客户端断开,这个方法会阻塞
                curSession.getBasicRemote().sendPing(ByteBuffer.wrap("ping".getBytes()));
                System.out.println("Ping End============>>>>>>>>>>");

            } catch (IOException e) {
                System.out.println("Fail========================================" + e.getMessage());
            }*/

//            System.out.println("DOTEST---------:"+curSession.getId() + curSession.isOpen());


//            try {
//
//            curSession.getBasicRemote().sendText("test a closed sessiong");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

        } else {
            System.out.println("Ping end session null============>>>>>>>>>>");

        }
    }


    @OnOpen
    public void onOpen(Session session, @PathParam("loggerName") String loggerName) {
        try {
            curSession = session;
            pipe.register(loggerName, session);
            curSession.getBasicRemote().sendText("Server accept connect successly.");
        } catch (IOException e) {
            e.printStackTrace();

        }
    }


    @OnClose
    public void onClose(Session session, @PathParam("loggerName") String loggerName) {
        System.out.println("****************on close start******************************session:"+session.isOpen());
        pipe.cancel(loggerName, session);
        System.out.println("****************on close end******************************session:"+session.isOpen());

    }


    @OnMessage
    public void onmessage(Session session, String message) {
        System.out.println("server message:" + message + "," + session.getId());

    }


    @OnError
    public void onError(Session session, Throwable t) throws Throwable {
        System.out.println("****************on error******************************");
        pipe.cancel(session);
    }


}
